<?php
/**
 * Created by PhpStorm.
 * User: Windows
 * Date: 2015/11/12
 * Time: 18:45
 */
class PrincipalController extends Controller
{

    private $_title;
    private $_keywords;
    private $_description;

    public function init()
    {
        parent::init();
        $user_info = $this->_session->offsetGet ( 'loginInfos' );
        $this->_view->userInfo=$user_info;
    }

    public function indexAction(){
        global $_getAreaNames,$_suppliyStateCfg;
        define('ITEM_PER_PAGE', 10);
        $this->_title = '现货资源';
        $this->_keywords = '现货资源';
        $this->_description = '现货资源';
        $url = "/principal/index";
        //分类
        $index = new IndexModel();
        $cate = $index->getCateInfo("cate",'','');
        //获取参数
        $page=empty($_GET['page']) ? 1 :htmlspecialchars(trim($_GET['page']) , ENT_QUOTES ,'utf-8');

        $kd=empty($_GET['kd']) ? '' :htmlspecialchars(trim($_GET['kd']) , ENT_QUOTES ,'utf-8');

        $cate_name=empty($_GET['cate_name']) ? '' :htmlspecialchars(trim($_GET['cate_name']) , ENT_QUOTES ,'utf-8');

        $cates_name=empty($_GET['cates_name']) ? '' :htmlspecialchars(trim($_GET['cates_name']) , ENT_QUOTES ,'utf-8');

        $currency_name=empty($_GET['currency_name']) ? '' :htmlspecialchars(trim($_GET['currency_name']) , ENT_QUOTES ,'utf-8');

        $area_id=empty($_GET['area_id']) ? '' :htmlspecialchars(trim($_GET['area_id']) , ENT_QUOTES ,'utf-8');

        $area_name=empty($_GET['area_name']) ? '' :htmlspecialchars(trim($_GET['area_name']) , ENT_QUOTES ,'utf-8');

        $region_name=empty($_GET['region_name']) ? '' :htmlspecialchars(trim($_GET['region_name']) , ENT_QUOTES ,'utf-8');

        $brand_name=empty($_GET['brand_name']) ? '' :htmlspecialchars(trim($_GET['brand_name']) , ENT_QUOTES ,'utf-8');


        $product_name=empty($_GET['product_name']) ? '' :htmlspecialchars(trim($_GET['product_name']) , ENT_QUOTES ,'utf-8');

        $orderby=empty($_GET['order']) ? '' :htmlspecialchars(trim($_GET['order']) , ENT_QUOTES ,'utf-8');

        $minprice=empty($_GET['minprice']) ? '' :htmlspecialchars(trim($_GET['minprice']) , ENT_QUOTES ,'utf-8');

        $maxprice=empty($_GET['maxprice']) ? '' :htmlspecialchars(trim($_GET['maxprice']) , ENT_QUOTES ,'utf-8');

        $list_search=empty($_GET['list_search']) ? '' :htmlspecialchars(trim($_GET['list_search']) , ENT_QUOTES ,'utf-8');

        $delivery_area=empty($_GET['delivery_area']) ? '' :htmlspecialchars(trim($_GET['delivery_area']) , ENT_QUOTES ,'utf-8');

        $condition = array();
        $conditions = array();
        $urls=array();
        if(!empty($cate_name)){
            $conditions[] = "pc.cate_name like '%{$cate_name}%'";
            $urls[]="cate_name={$cate_name}";
        }

        if(!empty($currency_name)){
            $conditions[] = "rc.name like '%{$currency_name}%'";
            $urls[]="currency_name={$currency_name}";
        }

        if(!empty($area_id)){
            $conditions[] = "iq.area_id = '{$area_id}'";
            $urls[]="area_id={$area_id}";
        }

        if(!empty($area_name)){
            $conditions[] = "r.region_name like '%{$area_name}%'";
            $urls[]="area_name={$area_name}";
        }
        $keyword_list_search=strtr($list_search, array('%'=>'\%'));
        if(!empty($list_search)){
            $conditions[] =" (p.product_name like '%{$keyword_list_search}%' or pc.cate_name like '%{$keyword_list_search}%' or pb.brand_name like '%{$keyword_list_search}%' or r.region_name like '%{$keyword_list_search}%' or iq.delivery_area like '%{$keyword_list_search}%')";
            $urls[]="list_search={$list_search}";
        }

        if(!empty($delivery_area)){
            $conditions[] = "iq.delivery_area like '%{$delivery_area}%'";
            $urls[]="delivery_area={$delivery_area}";
        }

        if(!empty($product_name)){
            $conditions[] = "p.product_name like '%{$product_name}%'";
            $urls[]="product_name={$product_name}";
        }

        if(!empty($brand_name)){
            $conditions[] = "pb.brand_name like '%{$brand_name}%'";
            $urls[]="brand_name={$brand_name}";
        }


        $having = "1=1";
        if(!empty($minprice)){
            $having .= " and min(iq.price) >= '{$minprice}'";
            $urls[]="minprice='{$minprice}'";
        }

        if(!empty($maxprice)){
            $having .= " and min(iq.price) <= '{$maxprice}'";
            $urls[]="maxprice={$maxprice}";
        }

        $url .= "?page=%d";
        $where= "1=1";
        $wheres= "1=1";
        if(empty($conditions))
        {
            $wheres  .= " AND iq.status= '{$_suppliyStateCfg['up']}'";
        } else {
            $wheres  .= " AND iq.status= '{$_suppliyStateCfg['up']}'"." AND ".implode(' AND ', $conditions);
        }

        //下面或者关系
        if(!empty($cates_name)){
            $condition[]= "pc.cate_name like '%{$cates_name}%'";
            $urls[]="cates_name={$cates_name}";
        }

        if(!empty($region_name)){
            $condition[] = "r.region_name like '%{$region_name}%'";
            $urls[]="region_name={$region_name}";
        }

        if(empty($condition))
        {
            $where  = '1=1 ';
        } else {
            $where  .= " AND ".implode(' AND ', $condition);
        }

        if(!empty($condition)){
            if(!empty($cate_name) || !empty($area_name)){
                $wheres.= " or (".$where.")";
            }else{
                $wheres.= " AND (".$where.")";
            }
        }

        if(!empty($urls)){
            $url.=  "&".implode('&',$urls);
        }
        $url.="&kd={$kd}&order={$orderby}";

        //实例化当前module
        $search = new SearchModel();
        //币种展示，这边从数据库读取，便于管理
        $CurrencyShow =  $search->getCurrencyShow("index_show='Y'");
        //这边还是要去查询地区
        $AreaShow = $search->getAreaShow("iq.status = '2' ");

        if(!empty($AreaShow)){
            foreach($AreaShow as $key=>$var){
                if(!empty($var['area_id']) && !empty($var['area_name'])){
                    $areas[] =  $var['area_id'];
                }
                unset($AreaShow[$key]);
            }
        }

        if(!empty($areas)){
            $AreaShow = array_unique($areas);
        }

        $Region =   new RegionModel();
        if(!empty($AreaShow)){
            foreach($AreaShow as $k=>$v){
                $AreaShowLIst[$k]['area_id'] = $v;
                $AreaShowLIst[$k]['area_name'] = $Region->getOneByIdAndName($v,"region_name");
            }
        }else{
            $AreaShowLIst = array();
        }
        $CountArea = count($AreaShowLIst);

        //这个功能去掉，交货地直接使用area_id
        //这边去查询一下交货地

//        $DeliveryShow = $search->getDeliveryShow("iq.area_id <> '' and iq.currency_id <> '' and iq.status = '2' ");
//        if(!empty($DeliveryShow)){
//            foreach($DeliveryShow as $key=>$var){
//                if(!empty($var['delivery_area'])){
//                    $delivery_areas[] =  Tools::substr($var['delivery_area'],0,2,"utf-8");
//                }
//                unset($DeliveryShow[$key]);
//            }
//        }
//        if(!empty($delivery_areas)){
//            $DeliveryShow = array_unique($delivery_areas);
//        }
//        var_dump($DeliveryShow);
        //这边去加载首页的数据
        if($orderby=='numdesc'){
            $order = "iq.num desc";
        }else if($orderby=='pricedesc'){
            $order = "min(iq.price) DESC";
        }else if($orderby=='priceasc'){
            $order = "min(iq.price) ASC";
        }else{
            $order = "iq.create_time desc";
        }

        $group = "iq.product_id";
        $totalItems =  $search->getPriceCountByWhere($wheres,$group,$having);
        $offset = 0;
        $page =  empty($page) ? 1 :$page;
        $offset = ($page - 1) * ITEM_PER_PAGE;
        if ($offset >= $totalItems) {
            $page = ceil ( $totalItems / ITEM_PER_PAGE );
            $offset = ($page - 1) * ITEM_PER_PAGE;
        }
        if ($offset < 0) {
            $offset = 0;
            $page = 1;
        }

        $data['list'] = $search->getPriceListByWhere($wheres,ITEM_PER_PAGE,$offset,$order,$group,$having);
        if(!empty($data['list'])){
            foreach($data['list'] as $key=>$var){
                $data['list'][$key]['price_num'] =count($search->getPriceBusinessByWhere("product_id = {$var['product_id']} and iq.status = '{$_suppliyStateCfg['up']}'"));
            }
        }

        $links = Pagination::createPage($url, ITEM_PER_PAGE, $page, $totalItems, 2 ,'_self',true);
        $linkpage = Tools::linkPage($url,  ITEM_PER_PAGE, $page, $totalItems, $target = '_self');
        $this->_view->kd = $kd;
        $this->_view->title = $this->_title;
        $this->_view->keywords  = $this->_keywords;
        $this->_view->description = $this->_description;
        $this->_view->_getAreaNames = $_getAreaNames;
        $this->_view->cate = $cate;
        $this->_view->data = $data['list'];
        $this->_view->CurrencyShow = $CurrencyShow;
        $this->_view->AreaShow = $AreaShowLIst;
//        $this->_view->DeliveryShow = $DeliveryShow;
        $this->_view->CountArea = $CountArea;
        $this->_view->links = $links;
        $this->_view->linkpage = $linkpage;

        $this->_view->page = $page;
        $this->_view->totalnum = $totalItems;
        $this->_view->cate_name = $cate_name;
        $this->_view->cates_name = $cates_name;
        $this->_view->currency_name = $currency_name;
        $this->_view->area_id = $area_id;
        $this->_view->area_name = $area_name;
        $this->_view->region_name = $region_name;
        $this->_view->brand_name = $brand_name;
        $this->_view->product_name = $product_name;
        $this->_view->order = $orderby;
        $this->_view->minprice = $minprice;
        $this->_view->maxprice = $maxprice;
        $this->_view->delivery_area  = $delivery_area ;
        $this->_view->list_search = $list_search;
    }

    public function emptyAction(){
        echo "1";
    }


}